package com.sh4.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sh4.dao.impl.BaseDaoImpl;
import com.sh4.dao.impl.EnumDaoImpl;
import com.sh4.entity.SystemEnum;
import com.sh4.service.EnumService;
import com.sh4.util.ContextHeader;

import net.sf.json.JSONObject;

@Service("enumServiceImpl")
@Transactional
public class EnumServiceImpl extends BaseDaoImpl<SystemEnum> implements EnumService{
	
	@Autowired
	EnumDaoImpl enumDao;
	
	@Value(value="${conf.companyCode}")
	private String companyCode;
	
	@Override
	public SystemEnum saveEnum(SystemEnum e) {
		
		if(StringUtils.isBlank(e.getId())) { //表示新增
			if("0".equals(e.getParentCode())) { //表示新增枚举项
				e.setEnumCode(companyCode + String.format("%02d", enumDao.enumCount(companyCode)));
				e.setCreateBy(ContextHeader.getUserCode());
				e.setCompanyCode(companyCode);
				e.setCreateDate(new Date());
			}else {
				e.setEnumCode(e.getParentCode() + String.format("%03d", enumDao.enumSonCount(e.getParentCode())));
				e.setCreateBy(ContextHeader.getUserCode());
				e.setCreateDate(new Date());
			}
		}
		enumDao.saveOrUpdate(e);
		return e;
	}

	@Override
	public Map<String , Object> list(int pageNO , int pageSize , JSONObject params) {
		Map<String , Object> result = new HashMap<String ,Object>();
		String hql = "from SystemEnum s where 1=1 and s.parentCode = ? order by s.createDate";
		result.put("dataList", enumDao.getPage(pageNO, pageSize, hql , params.getString("parentCode")));
		int total = 0;
		if("0".equals(params.getString("parentCode"))) {
			total = enumDao.enumCount(companyCode);
		}else{
			total = enumDao.enumSonCount(params.getString("parentCode"));
		}
		result.put("total", total);
		return result;
	}

	@Override
	public SystemEnum deleteEnum(SystemEnum e) {
		
//		e.setStatus(false);
//		e.setUpdateBy(ContextHeader.getUserCode());
//		e.setUpdateDate(new Date());
//		enumDao.saveOrUpdate(e);
		enumDao.delete(e);
		return e;
	}

	@Override
	public List<Map<String, Object>> getEnumList(String parentCode) {
		
		return enumDao.getEnumList(parentCode);
	}
	
	

}
